<template>
  <div>
    <p class="tip">
      虚拟滚动行校验，如果第一个参数为 true 则全量校验<br>
      <span class="red">（如果不指定数据，则默认只校验临时变动的数据，例如新增或修改...等）</span>
    </p>

    <vhb-toolbar :refresh="{query: findList}">
      <template #buttons>
        <vhb-button>
          <template #default>新增操作</template>
          <template #dropdowns>
            <vhb-button type="text" @click="insertEvent(null)">从第一行插入</vhb-button>
            <vhb-button type="text" @click="insertEvent(-1)">从最后插入</vhb-button>
            <vhb-button type="text" @click="insertEvent($refs.xTable.getData(100))">插入到 100 行</vhb-button>
            <vhb-button type="text" @click="insertEvent($refs.xTable.getData(2000))">插入到 2000 行</vhb-button>
          </template>
        </vhb-button>
        <vhb-button>
          <template #default>删除操作</template>
          <template #dropdowns>
            <vhb-button type="text" @click="$refs.xTable.removeCheckboxRow()">删除选中</vhb-button>
            <vhb-button type="text" @click="$refs.xTable.remove($refs.xTable.getData(0))">删除第一行</vhb-button>
            <vhb-button type="text" @click="$refs.xTable.remove($refs.xTable.getData($refs.xTable.getData().length - 1))">删除最后一行</vhb-button>
            <vhb-button type="text" @click="$refs.xTable.remove($refs.xTable.getData(100))">删除第 100 行</vhb-button>
          </template>
        </vhb-button>
        <vhb-button>
          <template #default>校验操作</template>
          <template #dropdowns>
            <vhb-button type="text" @click="validEvent">快速校验</vhb-button>
            <vhb-button type="text" @click="fullValidEvent">完整快速校验</vhb-button>
            <vhb-button type="text" @click="selectValidEvent">选中行校验</vhb-button>
          </template>
        </vhb-button>
        <vhb-button @click="getInsertEvent">获取新增</vhb-button>
        <vhb-button @click="getRemoveEvent">获取删除</vhb-button>
        <vhb-button @click="getUpdateEvent">获取修改</vhb-button>
      </template>
    </vhb-toolbar>

    <vhb-table
      border
      resizable
      show-overflow
      keep-source
      ref="xTable"
      height="300"
      :loading="loading"
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'row', showStatus: true}">
      <vhb-column type="checkbox" width="60"></vhb-column>
      <vhb-column type="seq" width="100"></vhb-column>
      <vhb-column field="name" title="Name" sortable width="200" :edit-render="{name: 'input'}"></vhb-column>
      <vhb-column field="age" title="Age" width="200" :edit-render="{name: 'input'}"></vhb-column>
      <vhb-column field="sex" title="Sex" width="200" :edit-render="{name: 'input'}"></vhb-column>
      <vhb-column field="rate" title="Rate" width="200"></vhb-column>
      <vhb-column field="region" title="Region" width="200"></vhb-column>
      <vhb-column field="time" title="Time" width="200"></vhb-column>
      <vhb-column field="address" title="Address" width="300" show-overflow></vhb-column>
      <vhb-column field="updateTime" title="UpdateTime" width="200"></vhb-column>
      <vhb-column field="createTime" title="CreateTime" width="200"></vhb-column>
    </vhb-table>

    <p class="demo-code">{{ $t('app.body.button.showCode') }}</p>

    <pre>
      <pre-code class="xml">{{ demoCodes[0] }}</pre-code>
      <pre-code class="javascript">{{ demoCodes[1] }}</pre-code>
    </pre>
  </div>
</template>

<script>
import VHBTable from 'vhb-table'

export default {
  data () {
    return {
      loading: false,
      validRules: {
        name: [
          { required: true, message: 'app.body.valid.rName' },
          { min: 3, max: 50, message: '名称长度在 3 到 50 个字符' }
        ],
        sex: [
          { required: true, message: '性别必须填写' }
        ]
      },
      demoCodes: [
        `
        <vhb-toolbar :refresh="{query: findList}">
          <template #buttons>
            <vhb-button>
              <template #default>新增操作</template>
              <template #dropdowns>
                <vhb-button type="text" @click="insertEvent(null)">从第一行插入</vhb-button>
                <vhb-button type="text" @click="insertEvent(-1)">从最后插入</vhb-button>
                <vhb-button type="text" @click="insertEvent($refs.xTable.getData(100))">插入到 100 行</vhb-button>
                <vhb-button type="text" @click="insertEvent($refs.xTable.getData(2000))">插入到 2000 行</vhb-button>
              </template>
            </vhb-button>
            <vhb-button>
              <template #default>删除操作</template>
              <template #dropdowns>
                <vhb-button type="text" @click="$refs.xTable.removeCheckboxRow()">删除选中</vhb-button>
                <vhb-button type="text" @click="$refs.xTable.remove($refs.xTable.getData(0))">删除第一行</vhb-button>
                <vhb-button type="text" @click="$refs.xTable.remove($refs.xTable.getData($refs.xTable.getData().length - 1))">删除最后一行</vhb-button>
                <vhb-button type="text" @click="$refs.xTable.remove($refs.xTable.getData(100))">删除第 100 行</vhb-button>
              </template>
            </vhb-button>
            <vhb-button>
              <template #default校验操作</template>
              <template #dropdowns>
                <vhb-button @click="validEvent">快速校验</vhb-button>
                <vhb-button @click="fullValidEvent">完整快速校验</vhb-button>
                <vhb-button @click="selectValidEvent">选中行校验</vhb-button>
              </template>
            </vhb-button>
            <vhb-button @click="getInsertEvent">获取新增</vhb-button>
            <vhb-button @click="getRemoveEvent">获取删除</vhb-button>
            <vhb-button @click="getUpdateEvent">获取修改</vhb-button>
          </template>
        </vhb-toolbar>

        <vhb-table
          border
          resizable
          show-overflow
          keep-source
          ref="xTable"
          height="300"
          :loading="loading"
          :edit-rules="validRules"
          :edit-config="{trigger: 'click', mode: 'row', showStatus: true}">
          <vhb-column type="checkbox" width="60"></vhb-column>
          <vhb-column type="seq" width="100"></vhb-column>
          <vhb-column field="name" title="Name" sortable width="200" :edit-render="{name: 'input'}"></vhb-column>
          <vhb-column field="age" title="Age" width="200" :edit-render="{name: 'input'}"></vhb-column>
          <vhb-column field="sex" title="Sex" width="200" :edit-render="{name: 'input'}"></vhb-column>
          <vhb-column field="rate" title="Rate" width="200"></vhb-column>
          <vhb-column field="region" title="Region" width="200"></vhb-column>
          <vhb-column field="time" title="Time" width="200"></vhb-column>
          <vhb-column field="address" title="Address" width="300" show-overflow></vhb-column>
          <vhb-column field="updateTime" title="UpdateTime" width="200"></vhb-column>
          <vhb-column field="createTime" title="CreateTime" width="200"></vhb-column>
        </vhb-table>
        `,
        `
        import VHBTable from 'vhb-table'
        
        export default {
          data () {
            return {
              loading: false,
              validRules: {
                name: [
                  { required: true, message: 'app.body.valid.rName' },
                  { min: 3, max: 50, message: '名称长度在 3 到 50 个字符' }
                ],
                sex: [
                  { required: true, message: '性别必须填写' }
                ]
              }
            }
          },
          created () {
            this.findList()
          },
          methods: {
            findList () {
              this.loading = true
              return new Promise(resolve => {
                setTimeout(() => {
                  const tableData = this.mockList(600)
                  // 阻断 vue 对大数组的监听，避免 vue 绑定大数据造成短暂的卡顿
                  if (this.$refs.xTable) {
                    this.$refs.xTable.loadData(tableData)
                  }
                  resolve()
                  this.loading = false
                }, 300)
              })
            },
            mockList (size) {
              const list = []
              for (let index = 0; index < size; index++) {
                list.push({
                  name: \`名称\${index}\`,
                  sex: '0',
                  num: 123,
                  age: 18,
                  num2: 234,
                  rate: 3,
                  address: 'shenzhen'
                })
              }
              return list
            },
            async validEvent () {
              const $table = this.$refs.xTable
              const errMap = await $table.validate().catch(errMap => errMap)
              if (errMap) {
                VHBTable.modal.message({ status: 'error', content: '校验不通过！' })
              } else {
                VHBTable.modal.message({ status: 'success', content: '校验成功！' })
              }
            },
            async fullValidEvent () {
              const errMap = await this.$refs.xTable.fullValidate()
              if (errMap) {
                const msgList = []
                Object.values(errMap).forEach(errList => {
                  errList.forEach(params => {
                    const { rowIndex, column, rules } = params
                    rules.forEach(rule => {
                      msgList.push(\`第 \${rowIndex + 1} 行 \${column.title} 校验错误：\${rule.message}\`)
                    })
                  })
                })
                VHBTable.modal.message({
                  status: 'error',
                  slots: {
                    default () {
                      return [
                        <div class="red" style="max-height: 400px;overflow: auto;">
                          {
                            msgList.map(msg => {
                              return <div>{ msg }</div>
                            })
                          }
                        </div>
                      ]
                    }
                  }
                })
              } else {
                VHBTable.modal.message({ status: 'success', content: '校验成功！' })
              }
            },
            async selectValidEvent () {
              const $table = this.$refs.xTable
              const selectRecords = $table.getCheckboxRecords()
              if (selectRecords.length > 0) {
                const errMap = await $table.validate(selectRecords).catch(errMap => errMap)
                if (errMap) {
                  VHBTable.modal.message({ status: 'error', content: '校验不通过！' })
                } else {
                  VHBTable.modal.message({ status: 'success', content: '校验成功！' })
                }
              } else {
                VHBTable.modal.message({ status: 'warning', content: '未选中数据！' })
              }
            },
            insertEvent (row) {
              let xTable = this.$refs.xTable
              const record = {
                checked: false
              }
              xTable.insertAt(record, row).then(({ row }) => {
                xTable.setActiveRow(row)
              })
            },
            getInsertEvent () {
              let insertRecords = this.$refs.xTable.getInsertRecords()
              VHBTable.modal.alert(insertRecords.length)
            },
            getRemoveEvent () {
              let removeRecords = this.$refs.xTable.getRemoveRecords()
              VHBTable.modal.alert(removeRecords.length)
            },
            getUpdateEvent () {
              let updateRecords = this.$refs.xTable.getUpdateRecords()
              VHBTable.modal.alert(updateRecords.length)
            }
          }
        }
        `
      ]
    }
  },
  created () {
    this.findList()
  },
  methods: {
    findList () {
      this.loading = true
      return new Promise(resolve => {
        setTimeout(() => {
          const tableData = this.mockList(600)
          // 阻断 vue 对大数组的监听，避免 vue 绑定大数据造成短暂的卡顿
          if (this.$refs.xTable) {
            this.$refs.xTable.loadData(tableData)
          }
          resolve()
          this.loading = false
        }, 300)
      })
    },
    mockList (size) {
      const list = []
      for (let index = 0; index < size; index++) {
        list.push({
          name: `名称${index}`,
          sex: '0',
          num: 123,
          age: 18,
          num2: 234,
          rate: 3,
          address: 'shenzhen'
        })
      }
      return list
    },
    async validEvent () {
      const $table = this.$refs.xTable
      const errMap = await $table.validate().catch(errMap => errMap)
      if (errMap) {
        VHBTable.modal.message({ status: 'error', content: '校验不通过！' })
      } else {
        VHBTable.modal.message({ status: 'success', content: '校验成功！' })
      }
    },
    async fullValidEvent () {
      const errMap = await this.$refs.xTable.fullValidate()
      if (errMap) {
        const msgList = []
        Object.values(errMap).forEach(errList => {
          errList.forEach(params => {
            const { rowIndex, column, rules } = params
            rules.forEach(rule => {
              msgList.push(`第 ${rowIndex + 1} 行 ${column.title} 校验错误：${rule.message}`)
            })
          })
        })
        VHBTable.modal.message({
          status: 'error',
          slots: {
            default () {
              return [
                <div class="red" style="max-height: 400px;overflow: auto;">
                  {
                    msgList.map(msg => {
                      return <div>{ msg }</div>
                    })
                  }
                </div>
              ]
            }
          }
        })
      } else {
        VHBTable.modal.message({ status: 'success', content: '校验成功！' })
      }
    },
    async selectValidEvent () {
      const $table = this.$refs.xTable
      const selectRecords = $table.getCheckboxRecords()
      if (selectRecords.length > 0) {
        const errMap = await $table.validate(selectRecords).catch(errMap => errMap)
        if (errMap) {
          VHBTable.modal.message({ status: 'error', content: '校验不通过！' })
        } else {
          VHBTable.modal.message({ status: 'success', content: '校验成功！' })
        }
      } else {
        VHBTable.modal.message({ status: 'warning', content: '未选中数据！' })
      }
    },
    insertEvent (row) {
      const xTable = this.$refs.xTable
      const record = {
        checked: false
      }
      xTable.insertAt(record, row).then(({ row }) => {
        xTable.setActiveRow(row)
      })
    },
    getInsertEvent () {
      const insertRecords = this.$refs.xTable.getInsertRecords()
      VHBTable.modal.alert(insertRecords.length)
    },
    getRemoveEvent () {
      const removeRecords = this.$refs.xTable.getRemoveRecords()
      VHBTable.modal.alert(removeRecords.length)
    },
    getUpdateEvent () {
      const updateRecords = this.$refs.xTable.getUpdateRecords()
      VHBTable.modal.alert(updateRecords.length)
    }
  }
}
</script>
